package com.common.controller;

import com.common.enums.ApiResult;
import com.common.exception.ErrorException;
import com.common.model.SystemApplicationModel;
import com.common.sevice.SystemApplicationService;
import com.common.sevice.SystemImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

/**
 * @Description:
 * @Date: 2025/7/24 13:27
 */
@RestController
@RequestMapping("/v1/system/image")
public class SystemImageController {

    @Autowired
    private SystemApplicationService systemApplicationService;

    @Autowired
    private SystemImageService systemImageService;

    /**
     * 生成镜像
     *
     * @param params
     * @return
     */
    @PostMapping("/generaImage")
    public ApiResult generaImage(@RequestBody Map<String, Object> params) throws IOException {
        String appId = (String) params.get("appId");
        Object saveUrl = params.get("saveUrl");
        if (ObjectUtils.isEmpty(saveUrl)) {
            throw new ErrorException("请选择要保存的镜像文件所在位置");
        }
        if (ObjectUtils.isEmpty(appId)) {
            throw new ErrorException("请选择具体要构建的应用");
        }
        SystemApplicationModel applicationModel = systemApplicationService.getById(appId);
        if (ObjectUtils.isEmpty(applicationModel)) {
            throw new ErrorException("应用不存在");
        }
        String dockerComposeCli = systemImageService.generaImage(params, applicationModel);
        //打包镜像
        //启动镜像
        return ApiResult.success(dockerComposeCli);
    }
}
